// API 配置
const API_BASE_URL = '/api'

// 封装fetch请求
async function apiRequest(endpoint: string, options: RequestInit = {}): Promise<any> {
  const url = `${API_BASE_URL}${endpoint}`
  
  // 检查是否是FormData，如果是则不设置Content-Type让浏览器自动设置
  const isFormData = options.body instanceof FormData
  const defaultOptions: RequestInit = {
    headers: isFormData ? {} : {
      'Content-Type': 'application/json',
    },
    credentials: 'include', // 支持cookies
  }

  try {
    const response = await fetch(url, { ...defaultOptions, ...options })
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const contentType = response.headers.get('content-type')
    if (contentType && contentType.includes('application/json')) {
      return await response.json()
    }
    
    return await response.text()
  } catch (error) {
    console.error('API request error:', error)
    throw error
  }
}

// API 接口定义
export const api = {
  // 测试连接
  testConnection: () => apiRequest('/'),
  
  // 安全评价相关
  evaluation: {
    // 获取评价列表
    list: (params?: any) => {
      const queryString = params ? new URLSearchParams(params).toString() : ''
      return apiRequest(`/evaluation/evaluations/${queryString ? '?' + queryString : ''}`)
    },
    
    // 创建新评价
    create: (data: any) => apiRequest('/evaluation/evaluations/create/', {
      method: 'POST',
      body: JSON.stringify(data)
    }),
    
    // 获取评价详情
    detail: (id: number) => apiRequest(`/evaluation/evaluations/${id}/`),
    
    // 更新评价
    update: (id: number, data: any) => apiRequest(`/evaluation/evaluations/${id}/`, {
      method: 'PUT',
      body: JSON.stringify(data)
    }),
    
    // 删除评价
    delete: (id: number) => apiRequest(`/evaluation/evaluations/${id}/`, {
      method: 'DELETE'
    }),
    
    // 获取默认指标值
    getDefaultIndicators: () => apiRequest('/evaluation/default-indicators/'),
    
    // 计算评价得分
    calculate: (id: number) => apiRequest(`/evaluation/evaluations/${id}/calculate/`),
    
    // 获取统计数据
    statistics: () => apiRequest('/evaluation/statistics/'),
    
    // 生成安全报告
    generateSafetyReport: (id: number) => apiRequest(`/evaluation/evaluations/${id}/generate-report/`),
    
    // 更新安全等级
    updateSafetyLevel: (id: number, data: { safety_level: string, comprehensive_score: number }) => 
      apiRequest(`/evaluation/evaluations/${id}/update-safety-level/`, {
        method: 'POST',
        body: JSON.stringify(data)
      }),
    
    // 获取安全报告列表
    getReportsList: (params?: any) => {
      const queryString = params ? new URLSearchParams(params).toString() : ''
      return apiRequest(`/evaluation/reports/${queryString ? '?' + queryString : ''}`)
    },

    
    // 导出报告
    exportReport: (id: number) => apiRequest(`/evaluation/evaluations/${id}/export/`),
    
    // 原有接口保持兼容
    getHistory: () => apiRequest('/evaluation/history/'),
    getReport: (id: string) => apiRequest(`/evaluation/report/${id}/`)
  },
  
  // 隐患管理
  hazard: {
    getList: (params?: any) => apiRequest('/hazard/list/', {
      method: 'GET'
    }),
    updateStatus: (id: string, status: string) => apiRequest(`/hazard/${id}/status/`, {
      method: 'PUT',
      body: JSON.stringify({ status })
    })
  },
  
  // 统计数据
  statistics: {
    getDashboard: () => apiRequest('/statistics/dashboard/')
  },
  
  // 用户管理
  user: {
    getProfile: () => apiRequest('/user/profile/'),
    login: (credentials: { username: string, password: string }) => 
      apiRequest('/api/users/login/', {
        method: 'POST',
        body: JSON.stringify(credentials)
      }),
    logout: () => apiRequest('/api/users/logout/', { method: 'POST' }),
    
    // 获取所有用户
    getAllUsers: (type?: string) => apiRequest(`/api/users/all/${type ? '?type=' + type : ''}`),
    
    // 获取用户统计
    getUserStatistics: () => apiRequest('/api/users/statistics/'),
    
    // 创建用户
    create: (userData: any) => apiRequest('/api/users/create/', {
      method: 'POST',
      body: JSON.stringify(userData)
    }),
    createUser: (userData: any) => apiRequest('/api/users/create/', {
      method: 'POST',
      body: JSON.stringify(userData)
    }),
    
    // 更新用户
    updateUser: (userId: string, userData: any) => apiRequest(`/api/users/update/${userId}/`, {
      method: 'PUT',
      body: JSON.stringify(userData)
    }),
    
    // 切换用户状态
    toggleUserStatus: (userId: string, userType: string) => apiRequest(`/api/users/toggle-status/${userId}/`, {
      method: 'PATCH',
      body: JSON.stringify({ type: userType })
    }),
    
    // 个人资料管理
    getUserProfile: (userId: string, userType: string) => apiRequest(`/api/users/${userId}/profile/?type=${userType}`),
    updateUserProfile: (userId: string, userData: any) => apiRequest(`/api/users/${userId}/profile/`, {
      method: 'PUT',
      body: JSON.stringify(userData)
    }),
    
    // 头像上传
    uploadAvatar: (userId: string, userType: string, avatarFile: File) => {
      const formData = new FormData()
      formData.append('avatar', avatarFile)
      formData.append('type', userType)
      
      return apiRequest(`/api/users/${userId}/avatar/`, {
        method: 'POST',
        body: formData,
        headers: {} // 让浏览器自动设置Content-Type for FormData
      })
    },
    
    // 修改密码
    changePassword: (userId: string, passwordData: any) => apiRequest(`/api/users/${userId}/password/`, {
      method: 'POST',
      body: JSON.stringify(passwordData)
    })
  },
  
  // 知识库管理
  knowledge: {
    // 获取知识列表
    getList: (params?: any) => {
      const queryString = params ? new URLSearchParams(params).toString() : ''
      return apiRequest(`/api/knowledge/list/${queryString ? '?' + queryString : ''}`)
    },
    
    // 上传知识文件
    upload: (formData: FormData) => apiRequest('/api/knowledge/upload/', {
      method: 'POST',
      body: formData,
      headers: {} // 让浏览器自动设置Content-Type
    }),
    
    // 获取知识详情
    getDetail: (id: string) => apiRequest(`/api/knowledge/detail/${id}/`),
    
    // 下载文件 - 直接指向静态文件
    downloadFile: (id: string) => apiRequest(`/api/knowledge/detail/${id}/`).then(response => {
      if (response.status === 'success' && response.data.filePath) {
        const link = document.createElement('a')
        link.href = `/knowledge_files/${response.data.filePath}`
        link.target = '_blank'
        link.download = response.data.fileName || 'download'
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      }
    }),
    
    // 删除知识
    delete: (id: string) => apiRequest(`/api/knowledge/delete/${id}/`, {
      method: 'DELETE'
    }),
    
    // 获取统计信息
    getStatistics: () => apiRequest('/api/knowledge/statistics/')
  },

  // 隐患追踪管理
  hazard: {
    // 获取隐患追踪列表
    getList: (params?: any) => {
      const queryString = params ? new URLSearchParams(params).toString() : ''
      return apiRequest(`/api/hazard/tracking/${queryString ? '?' + queryString : ''}`)
    },

    // 获取隐患追踪详情
    getDetail: (taskId: string) => apiRequest(`/api/hazard/tracking/${taskId}/`),

    // 创建隐患追踪任务
    create: (data: any) => apiRequest('/api/hazard/tracking/', {
      method: 'POST',
      body: JSON.stringify(data)
    }),

    // 更新隐患追踪任务
    update: (taskId: string, data: any) => apiRequest(`/api/hazard/tracking/${taskId}/`, {
      method: 'PUT',
      body: JSON.stringify(data)
    }),

    // 删除隐患追踪任务
    delete: (taskId: string) => apiRequest(`/api/hazard/tracking/${taskId}/`, {
      method: 'DELETE'
    }),

    // 从评价报告创建隐患任务
    createFromEvaluation: (data: any) => apiRequest('/api/hazard/create-from-evaluation/', {
      method: 'POST',
      body: JSON.stringify(data)
    }),

    // 获取隐患统计数据
    getStatistics: () => apiRequest('/api/hazard/statistics/'),

    // 上传隐患附件
    uploadAttachment: (taskId: string, formData: FormData) => apiRequest(`/api/hazard/tracking/${taskId}/upload/`, {
      method: 'POST',
      body: formData
    }),

    // 整改图片管理
    uploadRemediationImage: (taskId: string, imageFile: File) => {
      const formData = new FormData()
      formData.append('image', imageFile)
      
      return apiRequest(`/api/hazard/tracking/${taskId}/remediation-image/`, {
        method: 'POST',
        body: formData,
        headers: {} // 确保不设置Content-Type，让浏览器自动设置
      })
    },

    getRemediationImage: (taskId: string) => apiRequest(`/api/hazard/tracking/${taskId}/remediation-image/info/`),

    deleteRemediationImage: (taskId: string) => apiRequest(`/api/hazard/tracking/${taskId}/remediation-image/delete/`, {
      method: 'DELETE'
    })
  }
}

export default api
